package com.elesyser.main;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.elesyser.R;
import com.elesyser.alarm.AlarmReceiver;
import com.elesyser.util.CourseInfo;
import com.elesyser.util.CurriculumManager;
import com.elesyser.util.LoginHelper;
import com.elesyser.util.UserInfo;

import android.R.integer;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.DigitalClock;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class CurriculumActivity extends Activity {

	CurriculumManager cu;
	ListView curriculumlist;
	RelativeLayout progressLayout;
	TextView dayofweek;
	DigitalClock clock;

	Integer Today;
	Integer Current;
	String[] weekdays;
	String[] begintimes;
	String[] endtimes;

	String semestor = "";
	String academicYear = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.curriculumtable);
		curriculumlist = (ListView) findViewById(R.id.lv_curriculum);
		progressLayout = (RelativeLayout) findViewById(R.id.progresslayout);
		dayofweek = (TextView) findViewById(R.id.dayofweek);
		clock = (DigitalClock) findViewById(R.id.digitalClock1);

		Time time = new Time();
		time.setToNow();
		Integer year = time.year;
		int month = time.month;

		semestor = "";
		academicYear = "";
		if (month < 9) {
			academicYear = Integer.toString(year - 1) + "-" + year.toString();
		} else {
			academicYear = year.toString() + "-" + Integer.toString(year + 1);
		}

		if (month < 2 || month >= 9) {
			semestor = "1";
		} else {
			semestor = "2";
		}

		dayofweek.setText(year.toString());
		Today = time.weekDay == 0 ? 7 : time.weekDay;

		Current = Today;

		Resources res = getResources();
		weekdays = res.getStringArray(R.array.weekday);
		begintimes = res.getStringArray(R.array.classstarttime);
		endtimes = res.getStringArray(R.array.classendtime);
		new getCurriculum().execute(academicYear, semestor);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, Menu.FIRST + 1, Menu.NONE, "上一天");
		menu.add(Menu.NONE, Menu.FIRST + 2, Menu.NONE, "下一天");
		menu.add(Menu.NONE, Menu.FIRST + 3, Menu.NONE, "日期");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case Menu.FIRST + 1:
			ChangeDay(--Current);
			break;
		case Menu.FIRST + 2:
			ChangeDay(++Current);
			break;
		case Menu.FIRST + 3:
			LayoutInflater inflater = getLayoutInflater();
			View layout = inflater.inflate(R.layout.yearpickerdialog, null);
			new AlertDialog.Builder(this)
					.setTitle("选择学年")
					.setView(layout)
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									DatePicker dp = (DatePicker) findViewById(R.id.startyear);
									dayofweek.setText(Integer.toString(dp
											.getYear()));
								}
							}).setNegativeButton("取消", null).show();
			// new DatePickerDialog(this, callBack, year, monthOfYear,
			// dayOfMonth);
			// AlertDialog.Builder builder = new AlertDialog.Builder(this);
			// builder.set
		default:
			break;
		}
		return true;
	}

	private void ChangeDay(int day) {
		List<CourseInfo> Courses = null;
		try {
			Courses = cu.getCourses(day);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		setCurriculumTable(Courses);
	}

	private void setCurriculumTable(List<CourseInfo> result) {
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < result.size(); ++i) {
			Map<String, Object> ret = new HashMap<String, Object>();
			ret.put("tv_coursename", result.get(i).getCourseName());
			ret.put("tv_classroom", result.get(i).getLocation());
			ret.put("tv_begintime", begintimes[result.get(i).getBegin() - 1]);
			ret.put("tv_endtime", endtimes[result.get(i).getEnd() - 1]);
			//ret.put("tv_endtime", "tst");
			data.add(ret);
		}
		curriculumlist.setAdapter(new SimpleAdapter(CurriculumActivity.this,
				data, R.layout.curriculumitem, new String[] { "tv_coursename",
						"tv_classroom", "tv_begintime", "tv_endtime" },
				new int[] { R.id.tv_coursename, R.id.tv_classroom,
						R.id.tv_begintime, R.id.tv_endtime }));

		dayofweek.setText(weekdays[Current - 1]);
	}

	private class getCurriculum extends
			AsyncTask<String, Integer, List<CourseInfo>> {
		@Override
		protected void onPreExecute() {

		}

		@Override
		protected void onPostExecute(List<CourseInfo> result) {
			progressLayout.setVisibility(View.GONE);
			clock.setVisibility(View.VISIBLE);
			if (result != null) {
				setCurriculumTable(result);
			} else {
				return;
			}
			// Intent intent = new Intent(CurriculumActivity.this,
			// AlarmReceiver.class);
			//
			// intent.putExtra("message", "test");
			// PendingIntent pi = PendingIntent.getBroadcast(
			// CurriculumActivity.this, 0, intent, 0);
			//
			//
			// AlarmManager am = (AlarmManager)
			// getSystemService(Activity.ALARM_SERVICE);
			// Calendar calendar = Calendar.getInstance();
			// calendar.setTimeInMillis(System.currentTimeMillis());
			//
			// calendar.set(Calendar.SECOND, calendar.get(Calendar.SECOND) + 5);
			// am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi);

			try {
				FileInputStream fi = openFileInput(UserInfo.Username
						+ academicYear + semestor);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				// publishProgress(-1);
				e.printStackTrace();
				try {
					FileOutputStream fo = openFileOutput(UserInfo.Username
							+ academicYear + semestor, MODE_PRIVATE);
					try {
						ObjectOutputStream oop = new ObjectOutputStream(fo);
						cu.Persist(oop);
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
						Log.d("exception", "Persist failed");
					}
				} catch (FileNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}

		}

		protected void onProgressUpdate(Integer... values) {
			if (values[0] == -1) {
				Toast.makeText(CurriculumActivity.this, "network error!",
						Toast.LENGTH_LONG);
				CurriculumActivity.this.finish();
			}
		}

		@Override
		protected List<CourseInfo> doInBackground(String... params) {
			// TODO check the userinfo via the Internet
			try {
				FileInputStream fi = openFileInput(UserInfo.Username
						+ academicYear + semestor);
				ObjectInputStream oop = new ObjectInputStream(fi);
				cu = new CurriculumManager(oop);
			} catch (Exception e) {
				// TODO: handle exception
				cu = new CurriculumManager(params[0], params[1]);
			}

			List<CourseInfo> ret = null;
			try {
				ret = cu.getCourses(Today);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				publishProgress(-1);
			}
			return ret;
		}
	}
}
